<template>
  <div class="userInfo">
    <div class="userInfo-content">
      <el-tabs v-model="activeName" class="third-tabs">
        <el-tab-pane label="基本信息" name="info">
          <div v-if="!isSwitch">
            <Button type="primary" label="提交审核" @click="onSubmitInfoClick" />
            <Button label="取消" @click="onCancelEditClick" />
          </div>
          <Button type="primary" label="编辑" v-else @click="onEditInfoClick" />
          <InfoForm ref="userinfoRef" :infoForm="userInfo.form" :isSwitch="isSwitch" @complete="onComplete" />
        </el-tab-pane>

        <el-tab-pane label="类目信息" name="qualification">
          <div class="cate-box">
            <Button type="primary" label="变更类目" @click="onEditCateClick" v-if="isCate" />
            <Cate :isCate="isCate" @complete="onCateComplete" @change="onCancelChange" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="退货地址" name="address">
          <div class="delivery-adress">
            <Button type="primary" label="新增退货地址" @click="onAddadessClick" />
            <el-table ref="tableRef" :height="300" class="address_table" :data="userInfo.shipping" border>
              <el-table-column prop="shippingPerson" label="收货人" width="160" />
              <el-table-column prop="shippingMobile" label="联系电话" width="160" />
              <el-table-column prop="shippingAddressDetail" label="退货地址" />
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <div class="oper-btn">
                    <Link label="修改" @click="onEditAdressClick(scope.row)" />
                    <Link label="删除" @click="onDeletAdressClick(scope.row)" />
                    <Link label="设为默认" @click="onSetDefaultClick(scope.row)" v-if="scope.row.defaultFlag === 'NO'" />
                    <p v-else class="default_adress">默认地址</p>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>

  <Address v-model:visible="addressVisible" :addressForm="userInfo.addressForm" @change="addressChange" />
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/api'
import consts from '@/consts'
import formater from '@/formater.js'
import { calcTableHeight } from '@/assets/js/utils.js'
import Button from '@/components/button/button.vue'
import Link from '@/components/button/link.vue'
import Address from '@/components/address/add.vue'
import InfoForm from './components/user.vue'
import Cate from './components/cate.vue'
import Record from './components/record.vue'

const { tableRef, tableHeight } = calcTableHeight()
const router = useRouter()

const activeName = ref('info')
const addressVisible = ref(false)
const userinfoRef = ref(null)
const loading = ref(false)

const isSwitch = ref(true)
const isCate = ref(true)

const userInfo = reactive({
  form: {
    businessLicense: {},
    internetCertificate: {}
  },
  cardInfo: [],
  shipping: [],
  addressForm: {},
  goodsType: '',
  supplierCatList: [],
  operateList: []
})

let oldSupplierQualificationList = []
let otherQualificationList = []

const onSubmitInfoClick = async () => {
  try {
    await userinfoRef.value.submit()
    saveInfo()
  } catch (e) {}
}

const setDefault = async (row) => {
  let { err } = await api.post(`/medinstrument/third/supplier/setDefault?supplierShippingId=${row.supplierShippingId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    ElMessage.success('设置默认地址成功')
    loadData()
  }
}

const delAdress = async (row) => {
  let { err } = await api.post(`/medinstrument/third/supplier/delShippingDetail?supplierShippingId=${row.supplierShippingId}`)
  if (err) {
    ElMessage.error(err)
  } else {
    loadData()
  }
}

const saveInfo = async () => {
  let params = Object.assign({}, userInfo.form)

  let isQualificationModify = false

  oldSupplierQualificationList.forEach((e) => {
    if (params.businessLicense.id === e.id) {
      let qualification = params.businessLicense
      if (qualification.qualificationImg !== e.qualificationImg || qualification.effectiveDate !== e.effectiveDate || qualification.expiredDate !== e.expiredDate) {
        isQualificationModify = true
      }
    } else if (params.internetCertificate.id === e.id) {
      let qualification = params.internetCertificate
      if (qualification.qualificationImg !== e.qualificationImg) {
        isQualificationModify = true
      }
    } else {
      isQualificationModify = true
    }
  })

  if (isQualificationModify) {
    params.supplierQualificationList = [params.businessLicense, params.internetCertificate, ...otherQualificationList].filter((e) => e.qualificationImg)
  } else {
    delete params.supplierQualificationList
  }

  let { err } = await api.post('/medinstrument/third/supplier/updateInformation', params)
  if (err) {
    ElMessage.error(err)
  } else {
    params.supplierQualificationList ? ElMessage.success('证件信息编辑成功,待后台审核') : ElMessage.success('编辑成功')
    loadData()
    isSwitch.value = true
  }
}

const loadData = async () => {
  let { data, err } = await api.get('/medinstrument/third/supplier/information')
  if (err) {
    ElMessage.error(err)
  } else {
    userInfo.form = data

    // 营业执照
    userInfo.form.businessLicense = userInfo.form.supplierQualificationList.find((e) => e.qualificationType === 'BUSINESS_LICENSE') || {}

    // 医疗器械互联网销售备案证

    userInfo.form.internetCertificate = userInfo.form.supplierQualificationList.find((e) => e.qualificationType === 'INTERNET_CERTIFICATE') || {}

    //其他证件
    otherQualificationList = userInfo.form.supplierQualificationList.filter((e) => e.qualificationType !== 'INTERNET_CERTIFICATE' && e.qualificationType !== 'BUSINESS_LICENSE')

    //营业执照 医疗器械互联网销售备案证 原始数据

    oldSupplierQualificationList = [{ ...userInfo.form.businessLicense }, { ...userInfo.form.institutionLicense }]

    userInfo.shipping = data.supplierShippingDetailList
    userInfo.goodsType = data.goodsType
    userInfo.operateList = data.operateList
    userInfo.cardInfo = data.supplierQualificationList
  }
}

const onEditInfoClick = () => {
  isSwitch.value = false
}

const onAddadessClick = () => {
  userInfo.addressForm = { defaultFlag: 'NO' }
  addressVisible.value = true
}
const onEditAdressClick = (row) => {
  userInfo.addressForm = Object.assign({}, row)
  addressVisible.value = true
}
const onDeletAdressClick = (row) => {
  ElMessageBox.confirm(`您确认要删除吗(不可恢复)?`, '系统提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    showClose: false,
    closeOnClickModal: false,
    closeOnPressEscape: false
  })
    .then(() => {
      delAdress(row)
    })
    .catch(() => {})
}
const onSetDefaultClick = (row) => {
  setDefault(row)
}

const addressChange = () => {
  loadData()
}

const onCancelEditClick = () => {
  isSwitch.value = true
}

const onEditCateClick = () => {
  isCate.value = false
}

const onCateComplete = () => {
  isCate.value = true
}

const onCancelChange = () => {
  isCate.value = true
}

const onComplete = () => {
  loadData()
}

onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.userInfo {
  margin: 10px 15px 0 10px;
  padding: 20px;
  background: #fff;
  box-sizing: border-box;

  .userInfo-content {
    .third_button {
      height: 34px;
      padding: 9px 14px;
    }

    .delivery-adress {
      .el-table {
        margin-top: 20px;

        :deep(tr) {
          th,
          td {
            border-right: 0;
          }

          th {
            background-color: #fafafa;
          }
        }

        :deep(tr):hover {
          background-color: #f5f7fa;
        }

        :deep(thead) {
          font-size: 14px;
          color: var(--span-color-text);
          line-height: 16px;
          height: 47px;
        }

        :deep(tbody) {
          tr {
            height: 64px;
          }
        }
        .oper-btn {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .default_adress {
          color: var(--span-color-text);
          line-height: 16px;
          font-weight: 500;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
